package com.shqcjd.sinopecdemomobile.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.IntentEquipmentBean;
import com.shqcjd.sinopecdemomobile.model.pojo.RouteListBean;
import com.shqcjd.sinopecdemomobile.model.pojo.TaskCodeBean;
import com.shqcjd.sinopecdemomobile.ui.activity.EquipmentGroupActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.EquipmentInspectionActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.GenerateQRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.QRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.StateInspectionRecordActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.InspectionAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseFragment;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

/**
 * 巡检
 * Created by sy on 2019/3/14.
 */

public class InspectionFragment extends BaseFragment {
    @BindView(R.id.et_inspection_search)
    EditText etInspectionSearch;
    @BindView(R.id.rv_inspection)
    RecyclerView rvInspection;
    @BindView(R.id.ll_inspection_bottom)
    LinearLayout llInspectionBottom;
    @BindView(R.id.btn_generate_code)
    Button btnGenerateCode;
    @BindView(R.id.sr_inspection)
    SwipeRefreshLayout srInspection;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.btn_frag_inspection)
    Button btnFragInspection;

    private Context context;

    private InspectionAdapter inspectionAdapter;
    private List<RouteListBean.ItemsBean> adapterList = new ArrayList<>();
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private String strSearch = "";

    private int randomTaskId = -1;//随机任务码
    public static final int REQUEST_CODE = 100;
    private int total;


    public static InspectionFragment newInstance() {
        return new InspectionFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_inspection;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        context = getActivity();

        etInspectionSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString();
                refreshData();
            }
        });

        srInspection.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        btnFragInspection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createTask(1);
            }
        });
        refreshData();
    }


    private void visibleBottom() {
        if (adapterList.size() > 0) {
            llInspectionBottom.setVisibility(View.VISIBLE);
            rlIsnull.setVisibility(View.INVISIBLE);
        } else {
            llInspectionBottom.setVisibility(View.INVISIBLE);
            rlIsnull.setVisibility(View.VISIBLE);
        }
    }

    private void refreshData() {
        refreshOrLoadMore();
        srInspection.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (inspectionAdapter != null) {
            inspectionAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p + "");
        map.put("pageSize", Config.PAGE_TOTAL + "");
        map.put("patrol_root_name", strSearch);
        ApiService.routeListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RouteListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<RouteListBean> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            total = retData.data.total;
                            adapterList.addAll(retData.data.items);
                            if (inspectionAdapter == null) {
                                rvInspection.setLayoutManager(new WrapContentLinearLayoutManager(context));
                                inspectionAdapter = new InspectionAdapter(adapterList, context);
                                rvInspection.setAdapter(inspectionAdapter);

                                inspectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        Intent it = new Intent(context, StateInspectionRecordActivity.class);
                                        it.putExtra("rId", adapterList.get(position).id);
                                        startActivity(it);

                                    }
                                });

                                inspectionAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                    @Override
                                    public void onLoadMoreRequested() {
                                        int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                                        if (page >= pageSize) {
                                            rvInspection.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    inspectionAdapter.loadMoreEnd();
                                                }
                                            });
                                        } else {
                                            loadMoreData();
                                        }
                                    }
                                });
                            }
                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                inspectionAdapter.loadMoreComplete();
                            }
                            inspectionAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspection.setRefreshing(false);
                    }
                });
    }

    /**
     * 生成随机巡检任务码
     * t==1代表随机巡检
     * t==2代表生成随机巡检码
     */
    private void createTask(int t) {
        ApiService.getRandomTask()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TaskCodeBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<TaskCodeBean> responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (t == 1) {
                            randomTaskId = responseData.data.task_id;
                            RxPermissions permissions = new RxPermissions(getActivity());
                            permissions.setLogging(true);
                            permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            if (aBoolean) {
                                                startActivityForResult(new Intent(getActivity(), QRcodeActivity.class), REQUEST_CODE);
                                            } else {
                                                ToastUtils.show(getActivity(), "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                            }
                                        }
                                    });
                        } else {
                            String codeString = new Gson().toJson(responseData.data, TaskCodeBean.class);
                            Intent it = new Intent(getContext(), GenerateQRcodeActivity.class);
                            it.putExtra("QRcode", codeString);
                            startActivity(it);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void qCode(String kksStr) {
        if (randomTaskId != -1) {
            isInspectionData(kksStr);
        } else {
            Toast.makeText(context, "当前网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            qCode(value);
        }
    }

    private void isInspectionData(String kksStr) {
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), randomTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取巡检信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        hideWaitingDialog();
                        if (responseData.retCode == 10000) {
                            if (responseData.data.check_gps) {
                                RxPermissions permissions = new RxPermissions(getActivity());
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if (distance < 1000) {
                                                                if (responseData.data.isgroup) {
                                                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", randomTaskId);
                                                                    startActivity(it);
                                                                } else {
                                                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", randomTaskId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                            } else {
                                                                Toast.makeText(context, "当前位置距离巡检点超过了1000米", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(getActivity(), "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });

                            } else {
                                if (responseData.data.isgroup) {
                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", randomTaskId);
                                    startActivity(it);
                                } else {
                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                    it.putExtra("tId", randomTaskId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @OnClick(R.id.btn_generate_code)
    public void onViewClicked() {
        createTask(2);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}